package com.markerhub.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Data
@Component
@ConfigurationProperties(prefix = "markerhub.jwt")
public class JwtUtils {
    private int expire;
    private String secret;
    private String header;

    /***
     * 生成token
     */
    public String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000L * 60 * 60 * expire))
                .sign(Algorithm.HMAC256(secret));
    }
    /***
     * 接收token,验证token,并返回业务数据
     */

    public Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(secret))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }

    // jwt是否过期
    public boolean isTokenExpired(String jwt) {
        return JWT.decode(jwt)
                .getExpiresAt().before(new Date());
    }
}